﻿using Crawler.IRepositories;
using Crawler.Model;
using Microsoft.EntityFrameworkCore;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Crawler.Framework.Repositories
{
    public class Repository<T> : IRepository<T> where T : BaseModel, new()
    {
        protected readonly SqlSugarClient context;
        public Repository(SqlSugarClient context)
        {
            this.context = context;
        }

        public int Add(T t)
        {
            return context.Insertable(t).ExecuteCommand();
        }

        public T Find(int id)
        {
            return context.Queryable<T>().Where(t=>t.ID==id).First();
        }

        public IList<T> Find(Expression<Func<T, bool>> expression)
        {
            if (expression != null)
                return context.Queryable<T>().Where(expression).ToList();
            else
                return context.Queryable<T>().ToList();
        }

        public IEnumerable<T> GetAll()
        {
            return context.Queryable<T>().ToList();
        }

        public int Remove(T t)
        {
            return context.Deleteable<T>(t).ExecuteCommand();
        }

        public int Update(T t)
        {
            return context.Updateable<T>(t).ExecuteCommand();
        }
    }
}
